from django.core.files import File
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from django.utils.text import slugify
from glob import glob
from os.path import join, basename
from tinytag import TinyTag
from users.models import CCUser
from website.models import Artist, Album, BandMember, Song

class Command(BaseCommand):
    help = 'Load DB with songs.  Intended for development/testing purposes ONLY!'

    def add_arguments(self, parser):
        parser.add_argument('directory', type=str, help='Directory to search for audio files.  Search is recursive.')

    def handle(self, *args, **kwargs):
        directory = kwargs['directory']
        admin = CCUser.objects.get(username='admin')

        files = []
        for ext in ['*.mp3', '*.ogg', '*.opus', '*.flac', '*.m4a', '*.wav']:
            directory = join(directory, '**/')
            files.extend(glob(join(directory, ext), recursive=True))

        for f in files:
            tag = TinyTag.get(f)

            # Check to see if artist is loaded in db.  If not, load it.
            try:
                art = Artist.objects.get(name=tag.artist)
            except Artist.DoesNotExist:
                art = Artist.objects.create(handle=slugify(tag.artist), name=tag.artist)
                BandMember.objects.create(member=admin, artist=art)
                art.save()
                self.stdout.write("Artist %s added." % tag.artist)

            # Check to see if album is loaded in db.  If not, load it.
            try:
                alb = Album.objects.get(title=tag.album, artist=art)
            except Album.DoesNotExist:
                alb = Album.objects.create(title=tag.album, slug=slugify(tag.album), artist=art)
                alb.save()
                self.stdout.write("Album %s by %s added.\n" % (tag.album, tag.artist))

            # Check to see if song is loaded in db.  If not, load it.
            try:
                song = Song.objects.get(artist=art, album=alb, title=tag.title)
            except Song.DoesNotExist:
                song = Song.objects.create(artist=art, album=alb, title=tag.title, slug=slugify(tag.title))
                audio = File(open(f, "rb"))
                #save_path = join(art.handle, alb.slug)
                #save_path = join(save_path, basename(f))
                song.file.save(basename(f), audio, save=True)
                self.stdout.write("Song %s by %s on %s added.\n" % (tag.title, tag.artist, tag.album))
